import 'dart:io';
import 'package:app_expand/widget/pan_text.dart';
import 'package:flutter/material.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';

import '../../utils/screen_util.dart';

class SocketPage extends StatefulWidget {
  SocketPage({Key key}) : super(key: key);

  @override
  _SocketPageState createState() => _SocketPageState();
}

class _SocketPageState extends State<SocketPage> {

  IO.Socket socket;
  List messageList = [];
  bool showPhotoAction = false;
  ScrollController controller = ScrollController();
  TextEditingController message = TextEditingController();
  final ImagePicker picker = ImagePicker();
  

  @override
  void initState() { 
    super.initState();
    _connectServer();
  }

  /// 跟服务器建立连接
  _connectServer(){
    // 注意分组
    socket = IO.io('http://192.168.1.5:8000?roomid=1', <String, dynamic>{
      'transports': ['websocket'],
      // 'autoConnect': false
    });

    socket.on('connect', (_) {
      print('connect..');
      // socket.emit('toServer', 'this is flutter data');
    });
    socket.on('toClient', (data){
      setState(() {
        messageList.add({
          'server': true,
          'title': data['title'],
          'url': data['url']
        });
      });
      //改变滚动条的位置
      controller.jumpTo(controller.position.maxScrollExtent+80);
    });
  }

  // 广播
  doEmit(value) async{
    socket.emit('toServer', {'title': value, 'url': ''});
    // 发给服务器的消息没有包括自己发送的
    setState(() {
      //更新本地数据
      messageList.add({
        'server': false,
        'title': value,
        'url': ''
      });
    });
    controller.jumpTo(controller.position.maxScrollExtent+80);
  }

 /*拍照*/
  _takePhoto() async {
    PickedFile image = await picker.getImage(source: ImageSource.camera, maxWidth: 400);
    // 转换成File:
    File file = File(image.path);
    _uploadImage(file);
  }

  /*相册*/
  _openGallery() async {
    PickedFile image = await picker.getImage(source: ImageSource.gallery, maxWidth: 400);
    // 转换成File:
    File file = File(image.path);
    _uploadImage(file);
  }

   //上传图片
  _uploadImage(File _imageDir) async {
    //注意：dio3.x版本为了兼容web做了一些修改，上传图片的时候需要把File类型转换成String类型，具体代码如下
    setState(() {
      //更新数据
      messageList.add({"server": false, 'title': "", "url": _imageDir});
    });

    var fileDir=_imageDir.path;  
    FormData formData = FormData.fromMap({   
      "file":  await MultipartFile.fromFile(fileDir, filename: "xxx.jpg")     
    });

    var response = await Dio().post("http://192.168.1.5:8000/imgupload", data: formData);
    var data = response.data;
    var url = "http://192.168.1.5:8000${data["path"]}";    
    socket.emit('toServer', {"title": '', "url": url});
    controller.jumpTo(controller.position.maxScrollExtent + 80);
    //隐藏键盘
    FocusScope.of(context).requestFocus(FocusNode());
    setState(() { //注意
      showPhotoAction = false;
    });
  }  

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('即时通讯')
      ),
      body: Stack(
        children: [
          InkWell(
            child: Container(
              padding: EdgeInsets.only(bottom: 100),
              child: ListView.builder(
                controller: controller,
                itemCount: messageList.length,
                itemBuilder: (context, index) {
                  if(messageList[index]['server']){
                    var widget;
                    if(messageList[index]['url'] !='') {
                      widget = Container(
                        alignment: Alignment.centerLeft,
                        width: 100,
                        height: 100,
                        child: Image.file(messageList[index]['url']) //注意本地图片的写法
                      );
                    } else {
                      widget = Text('${messageList[index]['title']}', textAlign: TextAlign.start);
                    }
                    return ListTile(
                      leading: Icon(Icons.people),
                      title: widget
                    );
                  } else {
                    var widget;
                    if(messageList[index]['url'] !='') {
                      widget = Container(
                        alignment: Alignment.centerRight,
                        width: 100,
                        height: 100,
                        child: Image.file(messageList[index]['url']) //注意本地图片的写法
                      );
                    } else {
                      widget = Text('${messageList[index]['title']}', textAlign: TextAlign.end);
                    }
                    return ListTile(
                      trailing: Icon(Icons.person),
                      title: widget
                    );
                  }
                }
              )
            ),
            onTap: () {
              setState(() {
                showPhotoAction = false;
                // 隐藏键盘
                FocusScope.of(context).requestFocus(FocusNode());
              });
            }
          ),
          Positioned(
            bottom: 0,
            width: ScreenAdapter.width(750),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white
              ),
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: PanText(
                          controller: message,
                          onChange: (value) {
                            message.text = value;
                          },
                          onSubmitted: (key) {
                            doEmit(message.text);
                            message.text = '';
                          }
                        )
                      ),
                      Padding(
                        padding: EdgeInsets.all(ScreenAdapter.width(20)),
                        child: Container(
                          width: ScreenAdapter.width(68),
                          height: ScreenAdapter.width(68),
                          decoration: BoxDecoration(
                            color: Colors.black12,
                            borderRadius: BorderRadius.circular(
                              ScreenAdapter.width(68)
                            )
                          ),
                          child: InkWell(
                            child: Icon(Icons.add),
                            onTap: () {
                              setState(() {
                                showPhotoAction = true;
                              });
                            }
                          )
                        )
                      )
                    ]
                  ),
                  showPhotoAction ? Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: IconButton(
                          icon: Icon(Icons.photo_camera), 
                          onPressed: () {
                            _takePhoto();
                          }
                        )
                      ),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: IconButton(
                          icon: Icon(Icons.photo_library), 
                          onPressed: () {
                            _openGallery();
                          }
                        )
                      )
                    ]
                  ) : Container(height:0)
                ]
              )
            )
          )
        ],
      )
    );
  }
}